package com.rock.code.province.tj.coll;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.rock.code.common.util.*;
import com.rock.code.datacollconfig.business.dao.TbCollConfBusiDao;
import com.rock.code.datacollconfig.business.domain.TbCollConfBusi;
import com.rock.code.datacollconfig.coll.interfaces.CollDataItemInterface;
import org.apache.commons.lang3.StringUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

/**
 * @author zhangli
 * @version V1.0
 * @create 2019-10-15 16:14
 **/
public class TyCollImpl implements CollDataItemInterface {

    @Resource
    TbCollConfBusiDao tbCollConfBusiDao;

    @Override
    public void execute(String[] args) throws Exception {

        tbCollConfBusiDao = (TbCollConfBusiDao) SpringContextUtil.getBeanByClass(TbCollConfBusiDao.class);

        HashMap pramMap = new HashMap();
        pramMap.put("enable", "1");
        List<TbCollConfBusi> _list = tbCollConfBusiDao.getAllCollBusiConf(pramMap);
        for (TbCollConfBusi tbCollConfBusi : _list) {
            doBusiData(tbCollConfBusi);
            System.out.println(tbCollConfBusi.getBi_name());
        }

    }

    /***
     * @Author zhangli
     * @Description //TODO 调用听云接口返回数据
     * @Date 11:31 2019/10/16
     * @Param [tb_busi]
     * @return void
     **/
    private void doBusiData(TbCollConfBusi tb_busi){
        try{
            String headers = tb_busi.getBi_header();
            String url = tb_busi.getBi_url();
            String bi_param = tb_busi.getBi_param();

            JSONObject jsonObject = new JSONObject();

            if(StringUtils.isNotBlank(bi_param)){
                String []hs = bi_param.split("&");
                if(hs.length>0){
                    for (String kv : hs) {
                        String key_value[] = kv.split("=");
                        jsonObject.put(key_value[0],key_value[1]);
                    }
                }
            }
            JSONObject json = HttpRequestUtils.httpPostHeaderV1(url,jsonObject,headers);
            //解析json数据
            JSONObject transJson = parseJson(json);

            operation(tb_busi,transJson,tb_busi.getBi_url());
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    /***
     * @Author zhangli
     * @Description //TODO 解析新的json 对象，封装成一个新的可读的对象
     * @Date 18:32 2019/10/16
     * @Param [dataJson]
     * @return com.alibaba.fastjson.JSONObject
     **/
    private JSONObject parseJson(JSONObject dataJson){
        dataJson = (JSONObject) dataJson.get("chart");
        JSONArray jsonArray = (JSONArray) dataJson.get("dataset");

        JSONArray jsonServices = jsonArray.getJSONObject(0).getJSONObject("head").getJSONArray("serieses");
        JSONArray jsonCols = jsonArray.getJSONObject(0).getJSONObject("head").getJSONArray("cols");
        JSONArray jsonRows = jsonArray.getJSONObject(0).getJSONObject("head").getJSONArray("rows");
        JSONArray jsonDatas = jsonArray.getJSONObject(0).getJSONArray("data").getJSONArray(0);

        // start  封装新的json 对象
        JSONArray _addServices = new JSONArray();//封装成新的json对象
        JSONObject destJson = new JSONObject(true);//封装成新的json对象

        for (Object jsonService : jsonServices) {
            JSONObject _service = (JSONObject) jsonService;

            JSONObject dest_Json = new JSONObject(true);
            JSONArray _addDatas = new JSONArray();

            for (Object jsonData : jsonDatas) {
                JSONArray jy = (JSONArray) jsonData;
                for (int i = 0; i < jy.size(); i++) {
                    JSONArray sub_jy = (JSONArray) jy.get(i);
                    JSONObject sub_json = (JSONObject) jsonRows.get(i);

                    JSONObject _destJson = new JSONObject(true);
                    for (int i1 = 0; i1 < sub_jy.size(); i1++) {
                        String value = String.valueOf(sub_jy.get(i1)) ;
                        JSONObject sub_cols = (JSONObject) jsonCols.get(i1);
                        String col_name = sub_cols.getString("name");
//                        System.out.println(value+"-"+col_name+"-"+sub_json.get("name"));

                        _destJson.put("time",sub_json.get("name"));
                        _destJson.put(col_name,value);
                    }
                    _addDatas.add(_destJson);

                }
            }
            dest_Json.put("name",_service.get("name"));
            dest_Json.put("datas",_addDatas);
            _addServices.add(dest_Json);
            destJson.put("serieses",_addServices);
        }
        // end  封装新的json 对象
        System.out.println(destJson);
        return destJson;
    }
    /***
     * @Author zhangli
     * @Description //TODO 写入数据的接口
     * @Date 11:30 2019/10/16
     * @Param [tb_busi, dataArray]
     * @return void
     **/
    private void doMidlleData(TbCollConfBusi tb_busi,WriteKPI writeKPI,String time ,String value){
        String dataTime = writeKPI.getNowTime();
        String kpi_id = tb_busi.getKpi_id();
        String kbp = tb_busi.getKbp();
        String path = tb_busi.getPath();
        String bi_type = tb_busi.getBi_type();

        //解析json数据
        writeKPI.writeKPItoList(value, kpi_id, kbp, time, bi_type);


    }
    public void operation(TbCollConfBusi tb_busi,JSONObject opJson ,String operator){
        Vector<String> opr = new Vector();
        char _charArray [] = operator.toCharArray();
        for (char c : _charArray) {
            if(equalChar(c)!=null){
                opr.add(equalChar(c));
            }
        }
        if(!opr.isEmpty()) {//带+ - 运算符的运算 如：外部服务时间.性能+应用层时间.性能
            operator = operator.replaceAll("\\+", "#").replaceAll("\\-", "#");

            String[] sp = operator.split("#");
            Vector<String> src_Oprdata = new Vector<>();
            for (String _sp : sp) {
//            String [] sp_kv = _sp.split(".");
                src_Oprdata.add(_sp);

            }

            System.out.println(operator);
            Vector<Vector> coloction = new Vector<>();
            for (int i = 0; i < src_Oprdata.size(); i++) {
                Vector v = getDatas(src_Oprdata.get(i), opJson);
                coloction.add(v);
            }
            System.out.println(diguiOpr(coloction, opr));
            Vector<BigDecimal> destData = diguiOpr(coloction, opr);
            JSONArray jsonArray = opJson.getJSONArray("serieses").getJSONObject(0).getJSONArray("datas");
            //写入kpi 文件的地方
            WriteKPI writeKPI = new WriteKPI();
            for (int i = 0; i < destData.size(); i++) {
                String time = jsonArray.getJSONObject(i).getString("time");
                String value = String.valueOf(destData.get(i));
                doMidlleData(tb_busi, writeKPI, time, value);//写入文件
            }
            //写入到文件
            WriteFile wf = new WriteFile();
            wf.writeSevenStrucFile(tb_busi.getPath(), writeKPI.getVECTOR());
        }else {////不带+ - 运算符的运算 如：外部服务时间.性能
            Vector destData = getDatas(operator,opJson);
            System.out.println(destData);
            JSONArray jsonArray = opJson.getJSONArray("serieses").getJSONObject(0).getJSONArray("datas");
            //写入kpi 文件的地方
            WriteKPI writeKPI = new WriteKPI();
            for (int i = 0; i < destData.size(); i++) {
                String time = jsonArray.getJSONObject(i).getString("time");
                String value = String.valueOf(destData.get(i));
                doMidlleData(tb_busi, writeKPI, time, value);//写入文件
            }
            //写入到文件
            WriteFile wf = new WriteFile();
            wf.writeSevenStrucFile(tb_busi.getPath(), writeKPI.getVECTOR());
        }

    }

    private  Vector<BigDecimal> diguiOpr(Vector<Vector> vectors,Vector<String> opr){
        Vector<BigDecimal> _tmp = new Vector();
        Vector<BigDecimal> tmp = new Vector();
        for (int i = 0; i < vectors.size(); i++) {
            Vector<BigDecimal> dataV1  = vectors.get(i);
            if(i==0){
                _tmp = dataV1;
                continue;
            }

            String _opr = opr.get(i-1);
            for (int i1 = 0; i1 < _tmp.size(); i1++) {
                if(_opr.equals("+")){
                    double _value = _tmp.get(i1).doubleValue()+dataV1.get(i1).doubleValue();
                    tmp.add(new BigDecimal(_value));
                }else {
                    double _value = _tmp.get(i1).doubleValue()-dataV1.get(i1).doubleValue();
                    tmp.add(new BigDecimal(_value));
                }

            }
            Collections.copy(_tmp,tmp);
            tmp.clear();

            if(i==opr.size()){
                return _tmp;
            }

        }
        return _tmp;

    }


    private  Vector<BigDecimal> getDatas(String src_Oprdata,JSONObject dataJson){
        Vector<BigDecimal> _newVector =new Vector<>();
        JSONArray jsonArray = dataJson.getJSONArray("serieses");
        String _sv[] = src_Oprdata.split("\\.");
        for (Object obj : jsonArray) {
            JSONObject _json = (JSONObject)obj;
            if(!_json.getString("name").equalsIgnoreCase(_sv[0])){
                continue;
            }
            JSONArray datas =  _json.getJSONArray("datas");
            for (Object data : datas) {
                JSONObject json_data =(JSONObject)data;
                _newVector.add(json_data.getBigDecimal(_sv[1]));

            }
        }
        return _newVector;

    }
    public  String equalChar(char _char){
        if('+'==_char){
            return "+";
        }else if('-'==_char) {
            return "-";
        }else {
            return null;
        }

    }


}
